package com.zzyl.oss;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.zzyl.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Component
public class AliyunOssUtils {
    @Autowired
    private AliyunOssProperties properties;

    /**
     * 上传文件到aliyun oss
     * @param file
     * @return 文件url
     */
    public String uploadFile(MultipartFile file) {
        String domain = properties.getDomain();
        String endpoint = properties.getEndpoint();
        String bucketName = properties.getBucketName();
        String region = properties.getRegion();
        String accessKeyId = properties.getAccessKeyId();
        String secretAccessKey = properties.getSecretAccessKey();
        // 1.参数校验
        if(ObjUtil.isEmpty(file) || file.isEmpty()){
            throw new RuntimeException("上传文件不能为空");
        }
        String filename = file.getOriginalFilename();
        if(StrUtil.isEmpty(filename)){
            throw new RuntimeException("上传文件名错误！");
        }
        String path = null;
        OSS ossClient = null;
        try {
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, secretAccessKey);
            ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .credentialsProvider(credentialsProvider)
                    .region(region)
                    .build();
            //获取文件后缀.jpg
            String suffix = filename.substring(filename.lastIndexOf("."));
            //1.2.j3.fopsdf.jpg    --->   2025/02/22/0256e2648807434fa54dd66597c69e37.jpg
            filename = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            log.info("上传到服务器的文件名：{}", filename);
            ossClient.putObject(bucketName, filename, file.getInputStream());
            path = "https://" + bucketName + "." + domain + "/" + filename;
        } catch (Exception e) {
            log.error("文件上传失败，{}", e.getMessage(), e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return path;
    }
}